<template>
  <div class="pop-dialog-container">
    <div class="pop-dialog-main">
      <el-form label-position="right" :model="educationForm" :label-width="formLabelWidth" ref="educationFormRef" :rules="rules">
        <el-row>
          <el-col :span="11">
            <el-form-item label="员工姓名" prop="employeeName">
              <el-input v-model="educationForm.employeeName" placeholder="请选择员工姓名" readonly="readonly">
                <template #suffix>
                  <el-icon @click="findEmployee"><Search/></el-icon>
                </template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="学校名称" prop="schoolName">
              <el-input v-model="educationForm.schoolName" placeholder="请输入学校名称" maxlength="255"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="11">
            <el-form-item label="学历" prop="degree">
              <el-select v-model="educationForm.degree" placeholder="请选择学历">
                <el-option label="初中" :value="10"></el-option>
                <el-option label="高中" :value="20"></el-option>
                <el-option label="本科" :value="30"></el-option>
                <el-option label="硕士研究生" :value="40"></el-option>
                <el-option label="博士研究生" :value="50"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="开始日期" prop="startDate">
              <el-date-picker
                  v-model="educationForm.startDate" type="date" placeholder="开始日期" value-format="yyyy-MM-dd">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="11">
            <el-form-item label="结束日期" prop="endDate">
              <el-date-picker
                  v-model="educationForm.endDate" type="date" placeholder="结束日期" value-format="yyyy-MM-dd">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <div class="pop-dialog-footer">
      <el-row>
        <el-col :span="11" :offset="6">
          <div class="form-button-container">
            <el-button type="primary" @click="onSave">保存</el-button>
            <el-button @click="onReset">重置</el-button>
            <el-button type="primary" @click="onBack">关闭</el-button>
          </div>
        </el-col>
      </el-row>
    </div>
    <el-dialog v-model="employeeSelectorVisible" v-if="employeeSelectorVisible" title="员工基本信息选择器(双击行选中)" :top="dialogTop" :width="dialogWidth">
      <employee-selector @employee-selected-event="handleEmployeeSelectedEvent">
      </employee-selector>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import {defineEmits, defineProps, inject, onMounted, reactive, ref, toRefs} from 'vue';
import educationApi from '@/api/educationApi'
import type {FormInstance} from 'element-plus';
import {ElMessage} from 'element-plus'
import type {EducationForm} from "@/types/req/educationForm";
import type {Result} from '@/types/result'
import type {Education} from "@/types/resp/education";
import type {Id} from "@/types/id";
import { Search } from '@element-plus/icons-vue';
import EmployeeSelector from "@/views/employee/EmployeeSelector.vue";

const props = defineProps<Id>()
const educationFormRef = ref<FormInstance | null>(null);
const educationForm = reactive<EducationForm>({
  employeeId: 0,
  employeeName: '',
  schoolName: '',
  degree: undefined,
  startDate: '',
  endDate: '',
})
const employeeSelectorVisible = ref<boolean>(false)
const emit = defineEmits<{
  (e: 'resetEducationAddEvent'): void;
  (e: 'closeEducationAddEvent', data?: { search: boolean }): void;
}>()

const rules = reactive({
  employeeName: [
    { required: true, message: '请输入员工姓名', trigger: 'blur' }
  ],
  schoolName: [
    { required: true, message: '请输入学校名称', trigger: 'blur' }
  ],
  degree: [
    { required: true, message: '请输入学历', trigger: 'blur' }
  ],
});
const dialogTop = ref<string>('')
const dialogWidth = ref<string>('')
const formLabelWidth = ref<string>('')

onMounted(() => {
  if (props.id) {
    initEducationFormById(props.id)
  }
  const globalState = inject('globalState', {} as { dialogWidth?: string, dialogTop?: string, formLabelWidth?: string })
  if (!globalState) {
    throw new Error('globalState is not provided');
  }
  const globalStateRefs = toRefs(globalState)
  if (globalStateRefs.formLabelWidth) {
    formLabelWidth.value = globalStateRefs.formLabelWidth.value || ''
  }
  if (globalStateRefs.dialogWidth) {
    dialogWidth.value = globalStateRefs.dialogWidth.value || ''
  }
  if (globalStateRefs.dialogTop) {
    dialogTop.value = globalStateRefs.dialogTop.value || ''
  }
});

const initEducationFormById = async (id: number) => {
  const resp: Result<Education> = await educationApi.findById(id)
  if (resp && resp.code === 1 && resp.data) {
    Object.assign(educationForm, resp.data)
  }
}

const onReset = () => {
  if (educationFormRef.value) {
    educationFormRef.value.resetFields()
  }
  emit('resetEducationAddEvent')
}

const onSave = () => {
  if (!educationFormRef.value) {
    return
  }
  educationFormRef.value.validate(async (valid: boolean) => {
    if (valid) {
      const resp: Result<void> = await educationApi.save(educationForm)
      if (resp && resp.code === 1) {
        ElMessage.success('保存成功')
        emit('closeEducationAddEvent', {search: true})
      } else {
        ElMessage.error('保存失败:' + (resp.msg ? resp.msg : ''))
      }
    }
  })
}

const findEmployee = () => {
  employeeSelectorVisible.value = true
}

const handleEmployeeSelectedEvent = (selectedEmployee: any) => {
  employeeSelectorVisible.value = false
  if (selectedEmployee && 'employeeId' in selectedEmployee && educationForm.employeeId !== selectedEmployee['employeeId']) {
    educationForm.employeeId = selectedEmployee['employeeId']
    educationForm.employeeName = selectedEmployee['employeeName']
  }
}

const onBack = () => {
  emit('closeEducationAddEvent')
}
</script>

<style lang="scss">
</style>
